<template>
  <div>
    <el-upload
      class="upload-demo custom-upload"
      action="http://192.168.3.29:8081/upload"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :on-remove="handleRemove"
      list-type="picture-card"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过2MB
      </div>
    </el-upload>

    <div class="image-preview" v-if="fileList.length > 0">
      <img :src="fileList[0].url" alt="Preview" class="preview-image" />
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      fileList: [],
    }
  },
  methods: {
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      const isSizeValid = file.size / 1024 / 1024 < 2

      if (!isJpgOrPng) {
        this.$message.error('只能上传 JPG/PNG 格式的图片')
      }

      if (!isSizeValid) {
        this.$message.error('图片大小不能超过 2MB')
      }

      return isJpgOrPng && isSizeValid
    },
    handleRemove (file, fileList) {
      this.fileList = fileList
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-demo {
  border: 1px dashed #409eff;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  color: #999;
}

.el-upload__tip {
  margin-top: 10px;
}

.image-preview {
  margin-top: 20px;
  text-align: center;
}

.preview-image {
  max-width: 300px;
  max-height: 300px;
}
</style>
